1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#![allow(non_camel_case_types, non_snake_case)]

use crate::co;
use crate::decl::*;
use crate::guard::*;
use crate::kernel::{ffi, privs::*, proc};
use crate::prelude::*;

impl_handle! { HINSTANCE;
	/// Handle to an
	/// [instance](https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types#hinstance),
	/// same as `HMODULE`.
}

impl kernel_Hinstance for HINSTANCE {}

/// This trait is enabled with the `kernel` feature, and provides methods for
/// [`HINSTANCE`](crate::HINSTANCE).
///
/// Prefer importing this trait through the prelude:
///
/// ```no_run
/// use winsafe::prelude::*;
/// ```
pub trait kernel_Hinstance: Handle {
	/// [`EnumResourceLanguages`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-enumresourcelanguagesw)
	/// function.
	fn EnumResourceLanguages<F>(&self,
		resource_type: RtStr,
		resource_id: IdStr,
		func: F,
	) -> SysResult<()>
		where F: FnMut(LANGID) -> bool,
	{
		bool_to_sysresult(
			unsafe {
				ffi::EnumResourceLanguagesW(
					self.ptr(),
					resource_type.as_ptr(),
					resource_id.as_ptr(),
					proc::hinstance_enum_resource_languages::<F> as _,
					&func as *const _ as _,
				)
			},
		)
	}

	/// [`EnumResourceNames`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-enumresourcenamesw)
	/// function.
	///
	/// # Examples
	///
	/// ```no_run
	/// use winsafe::{self as w, prelude::*, co};
	///
	/// let hexe = w::HINSTANCE::LoadLibrary("hand.exe")?;
	///
	/// hexe.EnumResourceTypes(
	///     |res_type: w::RtStr| -> bool {
	///         let res_type2 = res_type.clone();
	///         hexe.EnumResourceNames(
	///             res_type,
	///             |name: w::IdStr| -> bool {
	///                 println!("Type: {}, name: {}", res_type2, name);
	///                 true
	///             },
	///         ).unwrap();
	///         true
	///     },
	/// )?;
	///
	/// // FreeLibrary() called automatically
	/// # w::SysResult::Ok(())
	/// ```
	fn EnumResourceNames<F>(&self,
		resource_type: RtStr,
		func: F,
	) -> SysResult<()>
		where F: FnMut(IdStr) -> bool,
	{
		bool_to_sysresult(
			unsafe {
				ffi::EnumResourceNamesW(
					self.ptr(),
					resource_type.as_ptr(),
					proc::hinstance_enum_resource_names::<F> as _,
					&func as *const _ as _,
				)
			},
		)
	}

	/// [`EnumResourceTypes`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-enumresourcetypesw)
	/// function.
	///
	/// # Examples
	///
	/// ```no_run
	/// use winsafe::{self as w, prelude::*, co};
	///
	/// let hexe = w::HINSTANCE::LoadLibrary("hand.exe")?;
	///
	/// hexe.EnumResourceTypes(
	///     |res_type: w::RtStr| -> bool {
	///         println!("Type {}", res_type);
	///         true
	///     },
	/// )?;
	///
	/// // FreeLibrary() called automatically
	/// # w::SysResult::Ok(())
	/// ```
	fn EnumResourceTypes<F>(&self, func: F) -> SysResult<()>
		where F: FnMut(RtStr) -> bool,
	{
		bool_to_sysresult(
			unsafe {
				ffi::EnumResourceTypesW(
					self.ptr(),
					proc::hinstance_enum_resource_types::<F> as _,
					&func as *const _ as _,
				)
			},
		)
	}

	/// [`FindResource`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-findresourcew)
	/// function.
	///
	/// For an example, see
	/// [`HINSTANCE::LockResource`](crate::prelude::kernel_Hinstance::LockResource).
	#[must_use]
	fn FindResource(&self,
		resource_id: IdStr,
		resource_type: RtStr,
	) -> SysResult<HRSRC>
	{
		ptr_to_sysresult_handle(
			unsafe {
				ffi::FindResourceW(
					self.ptr(),
					resource_id.as_ptr(),
					resource_type.as_ptr(),
				)
			},
		)
	}

	/// [`FindResourceEx`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-findresourceexw)
	/// function.
	///
	/// For an example, see
	/// [`HINSTANCE::LockResource`](crate::prelude::kernel_Hinstance::LockResource).
	#[must_use]
	fn FindResourceEx(&self,
		resource_id: IdStr,
		resource_type: RtStr,
		language: Option<LANGID>,
	) -> SysResult<HRSRC>
	{
		ptr_to_sysresult_handle(
			unsafe {
				ffi::FindResourceExW(
					self.ptr(),
					resource_id.as_ptr(),
					resource_type.as_ptr(),
					language.unwrap_or(LANGID::new(co::LANG::NEUTRAL, co::SUBLANG::NEUTRAL)).into(),
				)
			},
		)
	}

	/// [`GetModuleFileName`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamew)
	/// function.
	///
	/// # Examples
	///
	/// Retrieving the full path of currently running .exe file:
	///
	/// ```no_run
	/// use winsafe::{self as w, prelude::*};
	///
	/// let exe_name = w::HINSTANCE::NULL.GetModuleFileName()?;
	///
	/// println!("EXE: {}", exe_name);
	/// # w::SysResult::Ok(())
	/// ```
	#[must_use]
	fn GetModuleFileName(&self) -> SysResult<String> {
		let mut buf = [0; MAX_PATH];
		bool_to_sysresult(
			unsafe {
				ffi::GetModuleFileNameW(
					self.ptr(),
					buf.as_mut_ptr(),
					buf.len() as _,
				)
			} as _,
		).map(|_| WString::from_wchars_slice(&buf).to_string())
	}

	/// [`GetModuleHandle`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlew)
	/// function.
	///
	/// # Examples
	///
	/// Retrieving current module instance:
	///
	/// ```no_run
	/// use winsafe::{self as w, prelude::*};
	///
	/// let hinstance = w::HINSTANCE::GetModuleHandle(None)?;
	/// # w::SysResult::Ok(())
	/// ```
	#[must_use]
	fn GetModuleHandle(module_name: Option<&str>) -> SysResult<HINSTANCE> {
		ptr_to_sysresult_handle(
			unsafe {
				ffi::GetModuleHandleW(
					WString::from_opt_str(module_name).as_ptr(),
				)
			},
		)
	}

	/// [`GetProcAddress`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress)
	/// function.
	#[must_use]
	fn GetProcAddress(&self,
		proc_name: &str,
	) -> SysResult<*const std::ffi::c_void>
	{
		ptr_to_sysresult(
			unsafe {
				ffi::GetProcAddress(
					self.ptr(),
					vec_ptr(&str_to_iso88591(proc_name)),
				) as _
			},
		).map(|ptr| ptr as _)
	}

	/// [`LoadLibrary`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryw)
	/// function.
	#[must_use]
	fn LoadLibrary(lib_file_name: &str) -> SysResult<FreeLibraryGuard> {
		unsafe {
			ptr_to_sysresult_handle(
				ffi::LoadLibraryW(WString::from_str(lib_file_name).as_ptr()),
			).map(|h| FreeLibraryGuard::new(h))
		}
	}

	/// [`LoadResource`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadresource)
	/// function.
	///
	/// For an example, see
	/// [`HINSTANCE::LockResource`](crate::prelude::kernel_Hinstance::LockResource).
	#[must_use]
	fn LoadResource(&self, res_info: &HRSRC) -> SysResult<HRSRCMEM> {
		ptr_to_sysresult_handle(
			unsafe { ffi::LoadResource(self.ptr(), res_info.ptr()) },
		)
	}

	/// [`LockResource`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-lockresource)
	/// function.
	///
	/// This method should belong to [`HRSRCMEM`](crate::HRSRCMEM), but in order
	/// to make it safe, we automatically call
	/// [`HINSTANCE::SizeofResource`](crate::prelude::kernel_Hinstance::SizeofResource),
	/// so it's implemented here.
	///
	/// # Examples
	///
	/// The
	/// [Updating Resources](https://learn.microsoft.com/en-us/windows/win32/menurc/using-resources#updating-resources)
	/// example:
	///
	/// ```no_run
	/// use winsafe::{self as w, prelude::*, co};
	///
	/// const IDD_HAND_ABOUTBOX: u16 = 103;
	/// const IDD_FOOT_ABOUTBOX: u16 = 110;
	///
	/// let hexe = w::HINSTANCE::LoadLibrary("hand.exe")?;
	///
	/// let hres = hexe.FindResource(
	///     w::IdStr::Id(IDD_HAND_ABOUTBOX),
	///     w::RtStr::Rt(co::RT::DIALOG),
	/// )?;
	///
	/// let hres_load = hexe.LoadResource(&hres)?;
	/// let hres_slice_lock = hexe.LockResource(&hres, &hres_load)?;
	/// let hres_update = w::HUPDATERSRC::BeginUpdateResource("foot.exe", false)?;
	///
	/// hres_update.UpdateResource(
	///     w::RtStr::Rt(co::RT::DIALOG),
	///     w::IdStr::Id(IDD_FOOT_ABOUTBOX),
	///     w::LANGID::new(co::LANG::NEUTRAL, co::SUBLANG::NEUTRAL),
	///     hres_slice_lock,
	/// )?;
	///
	/// // EndUpdateResource() called automatically
	///
	/// // FreeLibrary() called automatically
	/// # w::SysResult::Ok(())
	/// ```
	#[must_use]
	fn LockResource(&self,
		res_info: &HRSRC,
		hres_loaded: &HRSRCMEM,
	) -> SysResult<&[u8]>
	{
		let sz = self.SizeofResource(res_info)?;
		unsafe {
			ptr_to_sysresult(ffi::LockResource(hres_loaded.ptr()))
				.map(|ptr| std::slice::from_raw_parts(ptr as _, sz as _))
		}
	}

	/// [`SizeofResource`](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-sizeofresource)
	/// function.
	///
	/// For an example, see
	/// [`HINSTANCE::LockResource`](crate::prelude::kernel_Hinstance::LockResource).
	#[must_use]
	fn SizeofResource(&self, res_info: &HRSRC) -> SysResult<u32> {
		match unsafe { ffi::SizeofResource(self.ptr(), res_info.ptr()) } {
			0 => Err(GetLastError()),
			sz => Ok(sz)
		}
	}
}